<template>
  <div class="login">
    <van-nav-bar title="登录" />

    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        required
        v-model="code"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLode"
          :loading="isLode"
          loading-text="加载中..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// import axios from '@/utils/request'
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      isLode: false,
      mobile: '13866224590',
      code: '246810',
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号码格式不正确'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式不正确'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async onSubmit() {
      this.isLode = true
      try {
        const res = await userLogin(this.mobile, this.code)
        // 给用户的vuex传值
        // this.$store.commit('user/setToken', res.data)
        this.setToken(res.data)
        this.$toast.success('登陆成功')

        // 根据传过来的参数判断跳到哪里
        const back = this.$route.query.back || '/user'
        const flag = this.$route.query.flag
        console.log(back)
        console.log(flag)
        console.log(this.$route.query.flag)
        console.log(this.$route)
        // 登录跳转到首页
        if (flag) {
          return this.$router.back()
        }
        this.$router.push(back)
      } catch (e) {
        this.$toast.fail('登录失败')
      }
      this.isLode = false
    }
  }
}
</script>

<style></style>
